<template>
  <div class="cu-common-layout">
    <div class="cu-common-layout-center">
      <el-row class="cu-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="校区品牌" prop="brand">
              <el-select v-model="query.brand" placeholder="">
                <el-option :key="item.id" :label="item.fullName" :value="item.enCode" v-for="item in brandOptions" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="校区信息">
              <el-select v-model="query.campusId" placeholder="请选择校区" filterable clearable :loading="campusLoading" @focus="loadCampusOptions">
                <el-option v-for="(item, index) in campusOptions" :key="index" :label="item.fullName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="校区类型">
              <el-select v-model="query.campusType" placeholder="" clearable>
                <el-option v-for="item in campusTypeOptions" :key="item.id" :label="item.fullName" :value="item.enCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="showAll">
            <el-col :span="6">
              <el-form-item label="校区区域">
                <custom-address v-model="query.area" :multiple="true" />
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
              <el-button type="text" icon="el-icon-arrow-down" @click="showAll = true" v-if="!showAll">展开</el-button>
              <el-button type="text" icon="el-icon-arrow-up" @click="showAll = false" v-else>收起</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="cu-common-layout-main cu-flex-main">
        <div class="cu-common-head">
          <div class="cu-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh cu-common-head-icon" :underline="false" @click="reset()" />
            </el-tooltip>
            <screenfull isContainer />
          </div>
        </div>
        <custom-table v-loading="listLoading" :data="list">
          <el-table-column label="招商编码" prop="joinCode" align="center" v-if="custom.hasP('joinCode')" width="100" />
          <el-table-column label="校区名称" prop="campusName" v-if="custom.hasP('campusName')" width="200" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.shortName + '(' + scope.row.enCode + ')' }}
            </template>
          </el-table-column>
          <el-table-column label="行政区域" prop="regions" width="140" v-if="custom.hasP('regions')" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.province + '/' + scope.row.city }}
            </template>
          </el-table-column>
          <el-table-column label="投资人" prop="investors" width="140" show-overflow-tooltip />
          <el-table-column label="校区类型" prop="campusType" width="80" align="center">
            <template slot-scope="scope">
              {{ scope.row.campusType | dynamicCodeText(campusTypeOptions) }}
            </template>
          </el-table-column>
          <el-table-column prop="campusStatus" label="状态" align="center" width="80">
            <template slot-scope="scope">
              <el-tag size="mini" v-if="scope.row.campusStatus == 'preparation'" key="筹备" type="" effect="dark">
                筹备
              </el-tag>
              <el-tag size="mini" v-if="scope.row.campusStatus == 'normal'" key="正常" type="success" effect="dark">
                正常
              </el-tag>
              <el-tag size="mini" v-if="scope.row.campusStatus == 'expires'" key="到期" type="info" effect="dark">
                待续费
              </el-tag>
              <el-tag size="mini" v-else-if="scope.row.campusStatus == 'suspended'" key="暂停" type="warning" effect="dark">
                暂停
              </el-tag>
              <el-tag size="mini" v-else-if="scope.row.campusStatus == 'close'" key="闭校" type="danger" effect="dark">
                闭校
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="档案编号" prop="fileNo" align="center" v-if="custom.hasP('fileNo')" width="120" />
          <el-table-column label="合同类型" prop="type" align="center" v-if="custom.hasP('type')" width="80">
            <template slot-scope="scope">
              {{ scope.row.type | dynamicCodeText(typeOptions) }}
            </template>
          </el-table-column>

          <el-table-column label="加盟费" prop="franchise" align="right" v-if="custom.hasP('franchise')" width="100">
            <template slot-scope="scope">
              <el-popover v-if="scope.row.franchise != 0" trigger="hover" placement="top">
                <p>特许经营费用: {{ scope.row.contract }}</p>
                <p>云平台使用费: {{ scope.row.cloudPlatform }}</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium">{{ scope.row.franchise }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="续约费" prop="renewal" align="right" v-if="custom.hasP('renewal')" width="100" />
          <el-table-column label="保证金" prop="deposit" align="right" v-if="custom.hasP('deposit')" width="100" />
          <el-table-column label="签约日期" prop="signingDate" align="center" v-if="custom.hasP('signingDate')" :formatter="custom.tableDateFormat" width="100" />
          <el-table-column label="开始日期" prop="startDate" align="center" v-if="custom.hasP('startDate')" :formatter="custom.tableDateFormat" width="100" />
          <el-table-column label="截止日期" prop="endDate" align="center" v-if="custom.hasP('endDate')" :formatter="custom.tableDateFormat" width="100" />
          <el-table-column label="应收金额" prop="receivable" align="right" v-if="custom.hasP('receivable')" width="80" />
          <el-table-column label="实收金额" prop="actual" align="right" v-if="custom.hasP('actual')" width="80" />
          <el-table-column label="支付情况" prop="isPayed" align="left" v-if="custom.hasP('isPayed')" width="80">
            <template slot-scope="scope">
              {{ scope.row.isPayed | dynamicCodeText(isPayedOptions) }}
            </template>
          </el-table-column>
          <el-table-column label="政策" prop="policy" align="left" v-if="custom.hasP('policy')" show-overflow-tooltip />
          <el-table-column label="创建用户" prop="createUserName" align="left" v-if="custom.hasP('createUserName')" width="80" show-overflow-tooltip />
          <el-table-column label="创建时间" prop="createTime" align="center" v-if="custom.hasP('createTime')" :formatter="custom.tableDateTimeFormat" width="120" />
          <el-table-column label="操作" fixed="right" width="100" align="center">
            <template slot-scope="scope">
              <!--              <el-button type="text" @click="addOrUpdateHandle(scope.row.id)" v-has="'btn_edit'">缴费</el-button>-->
              <el-button type="text" size="mini" @click="addOrUpdateHandle(scope.row.id)">编辑</el-button>
            </template>
          </el-table-column>
        </custom-table>
        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
      </div>
      <custom-form v-if="formVisible" ref="CustomForm" @refresh="refresh" />
    </div>
  </div>
</template>
<script>
import request from '@/utils/request'
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
import CustomForm from './Form'
import { getCampusSelector } from '@/api/campus/campus'
export default {
  components: { CustomForm },
  data() {
    return {
      query: {
        campusId: undefined,
        brand: 'bell',
        campusType: 'franchisee',
        isPayed: undefined
      },
      showAll: false,
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'fileNo'
      },
      formVisible: false,
      exportBoxVisible: false,
      columnList: [{ prop: 'campusId', label: '校区' }, { prop: 'startDate', label: '开始日期' }, { prop: 'endDate', label: '截止日期' }, { prop: 'receivable', label: '应收金额' }, { prop: 'actual', label: '实收金额' }, { prop: 'policy', label: '政策' }, { prop: 'createUserName', label: '创建用户' }, { prop: 'createTime', label: '创建日期' }],
      campusOptions: [],
      campusLoading: false,
      isPayedOptions: [],
      typeOptions: [],
      campusTypeOptions: [],
      brandOptions: [],
      campusStatusOptions: []
    }
  },
  computed: {},
  created() {
    this.getIsPayedOptions()
    this.getTypeOptions()
    this.getBrandOptionsOptions()
    this.getCampusTypeOptions()
    this.getCampusStatusOptions()
    this.initData()
  },
  methods: {
    getBrandOptionsOptions() {
      getDictionaryDataSelector('Brand').then(res => {
        this.brandOptions = res.data.list
      })
    },
    getIsPayedOptions() {
      getDictionaryDataSelector('PayStatus').then(res => {
        this.isPayedOptions = res.data.list
      })
    },
    getCampusTypeOptions() {
      getDictionaryDataSelector('CampusType').then(res => {
        this.campusTypeOptions = res.data.list
      })
    },
    getCampusStatusOptions() {
      getDictionaryDataSelector('CampusStatus').then(res => {
        this.campusStatusOptions = res.data.list
      })
    },
    getTypeOptions() {
      getDictionaryDataSelector('SignType').then(res => {
        this.typeOptions = res.data.list
      })
    },
    /**
     * 异步加载校区下拉选项
     * - 使用 getCampusSelector() 接口拉取校区数据
     * - 管理加载状态：campusLoading
     * - 错误时提示并清空选项
     */
    async loadCampusOptions() {
      try {
        this.campusLoading = true
        const params = {}
        if (this.query.brand) params.brand = this.query.brand
        params.fields = 'id,fullName'
        const res = await getCampusSelector(params)
        this.campusOptions = Array.isArray(res.data) ? res.data : []
      } catch (err) {
        console.error('加载校区下拉选项失败:', err)
        this.campusOptions = []
        this.$message && this.$message.error('校区选项加载失败')
      } finally {
        this.campusLoading = false
      }
    },
    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      request({
        url: `/api/finance/contract`,
        method: 'GET',
        data: query
      }).then(res => {
        this.list = res.data.list
        this.total = res.data.pagination.total
        this.listLoading = false
      })
    },

    addOrUpdateHandle(row, isDetail) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.CustomForm.init(row, isDetail)
      })
    },
    exportData() {
      this.exportBoxVisible = true
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.columnList)
      })
    },
    download(data) {
      let query = { ...data, ...this.listQuery, ...this.query }
      request({
        url: `/api/system/contract/Actions/Export`,
        method: 'GET',
        data: query
      }).then(res => {
        if (!res.data.url) return
        window.location.href = this.define.comUrl + res.data.url
        this.$refs.ExportBox.visible = false
        this.exportBoxVisible = false
      })
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'fileNo'
      }
      this.initData()
    },
    refresh(isrRefresh) {
      this.formVisible = false
      if (isrRefresh) this.reset()
    },
    reset() {
      this.query = {
        campus: undefined,
        brand: 'bell',
        campusType: 'franchisee',
        isPayed: undefined
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'fileNo'
      }
      this.initData()
    }
  }
}
</script>
<style lang="scss" scoped>
.main {
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding: 0 0 10px;
  >>> .el-table {
    flex: 1;
    border-top: none;
  }
}
</style>
